<template>
  <div>
    <div>
      <!-- 账号密码登录 -->
      <div>
        <nut-config-provider
          :theme-vars="{
            cellBoxShadow: 'none',
            cellPadding: '23rpx 0'
          }"
        >
          <nut-form
            label-position="top"
            ref="validateForm"
            :model-value="accountForm"
          >
            <nut-form-item
              :show-error-line="false"
              :rules="rules.username"
              label="用户名"
              prop="username"
            >
              <nut-input
                :input-style="passwordInputStyle"
                :border="false"
                v-model="accountForm.username"
                class="nut-input-text"
                placeholder="请输入账号"
              />
            </nut-form-item>
            <nut-form-item
              :show-error-line="false"
              :rules="rules.password"
              label="密码"
              prop="password"
            >
              <nut-input
                :input-style="passwordInputStyle"
                :border="false"
                v-model="accountForm.password"
                class="nut-input-text"
                :clearable="false"
                type="password"
                placeholder="请输入密码"
              />
            </nut-form-item>
            <div mt-40rpx>
              <nut-button
                :custom-color="!enablefetch ? disabledStyle : fetchStyle"
                block
                :loading="loading"
                class="submit"
                type="primary"
                @click="submit"
              >
                登录
              </nut-button>
            </div>
          </nut-form>
        </nut-config-provider>
      </div>
      <verifyModule
        v-if="enableVerifyModule"
        ref="verificationRef"
        class="verification"
        business="LOGIN"
        @send="verification"
      />
    </div>
    <nut-toast ref="toastRef" />
  </div>
</template>
<script setup lang="ts">
import { userLogin } from '@/api/login'
import {
  disabledStyle,
  fetchStyle,
  passwordInputStyle,
  saveTokenAndRefresh
} from '@/components/useful-template/login/common'
import verifyModule from '@/components/verification/verification.vue' // 验证码模块
import { useStore } from '@/store'
import { Md5 } from 'ts-md5'
import type { ToastInst } from 'nutui-uniapp'
const store = useStore()
const enableVerifyModule = ref(false) // 是否展示验证码模块

const loading = ref<boolean>(false)
const validateForm = ref<any>('') // 表单
const verificationRef = ref<any>(null) // 验证码模块
const clientType = ref<string>('') // 客户端类型
const enablefetch = ref<boolean>(false)
const toastRef = ref<ToastInst>() // toast
const emit = defineEmits(['verify'])
const props = defineProps({
  // 是否只验证
  verify: {
    type: Boolean,
    default: false
  }
})
// 账户登录
const accountForm = ref({
  username: '',
  password: ''
})
watch(
  accountForm,
  (val) => {
    if (val.username && val.password) {
      enablefetch.value = true
    } else {
      enablefetch.value = false
    }
  },
  { deep: true, immediate: true }
)

const rules = {
  username: [
    {
      required: true,
      message: '账号不能为空',
      trigger: 'change'
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'change'
    }
  ]
}

// 调用验证码进行验证
function getVerify() {
  enableVerifyModule.value = true
  setTimeout(() => {
    verificationRef.value.hide()
  }, 500)
}
// 验证
async function verification(val: string) {
  const flag = val === store.access.verificationKey
  if (flag) {
    enableVerifyModule.value = false
    login()
  }
}

// 用户登录
async function login() {
  console.log(accountForm.value.username)
  console.log(accountForm.value.password)
  const res = await userLogin({
    username: accountForm.value.username,
    password: Md5.hashStr(accountForm.value.password)
  })
  loading.value = false

  if (res.data.success) {
    emit('verify', res.data.result)
    if (props.verify) return
    saveTokenAndRefresh(res.data.result.token)
  }
}

function submit() {
  loading.value = true
  validateForm.value.validate().then(({ valid }: any) => {
    if (valid) {
      getVerify()
    } else {
      loading.value = false
    }
  })
}

onMounted(() => {
  // #ifdef APP-PLUS
  clientType.value = 'APP'
  // #endif
  // #ifdef H5
  clientType.value = 'H5'
  // #endif
})
</script>
<style>
page {
  background: #fff;
}
</style>
<style lang="scss" scoped>
:root,
page {
  --nut-cell-box-shadow: none;
}

.nut-cell-group__wrap {
  box-shadow: none !important;
}
</style>
